package pers.corvey.studyjava.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import pers.corvey.studyjava.model.Question;
import pers.corvey.studyjava.model.form.QuestionForm;
import pers.corvey.studyjava.model.json.QuestionAnswerJson;
import pers.corvey.studyjava.service.QuestionService;

@Controller
@RequestMapping("/tests/{testId}/questions")
public class QuestionController {

    @Autowired
    private QuestionService questionService;
    
    @GetMapping(headers="Accept=text/html")
    public String showQuestions() {
        return "forward://html/startTest.html";
    }
    
    @GetMapping(value="/addQuestion", headers="Accept=text/html")
    public String showAdd() {
        return "forward://addQuestion.html";
    }
    
    @GetMapping
    @ResponseBody
    public Iterable<Question> getQuestions(@PathVariable String testId) {
        return questionService.getQuestions(testId);
    }
    
    @GetMapping("/{questionId}")
    @ResponseBody
    public Question getQuestionById(@PathVariable String questionId) {
        return questionService.getQuestionById(questionId);
    }
    
    @PostMapping
    @ResponseBody
    public Question createQuestion(@PathVariable String testId, 
            @RequestBody QuestionForm questionForm) {
        System.out.println(testId);
        questionForm.validate();
        Question question = questionForm.toQuestion();
        question.setTestId(testId);
        return questionService.createQuestion(question);
    }
    
    @GetMapping("/answers")
    @ResponseBody
    public List<QuestionAnswerJson> getAnswers(@PathVariable String testId) {
        return questionService.getAnswersByTestId(testId);
    }
}
